package com.kgc.scd.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.kgc.scd.bean.SearchHistory;
import com.kgc.scd.contant.SearchHistoryConstant;

import com.kgc.scd.mapper.SearchHistoryMapper;
import com.kgc.scd.service.SearchService;
import com.kgc.scd.util.RedisUtils;
import com.kgc.scd.util.RequestResult;
import com.kgc.scd.util.ResultBuildUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;


/**
 * Created On : 2022/6/10.
 * <p>
 * Author     : hi
 * <p>
 * Description: 历史数据
 */
@Slf4j
@RestController
public class SearchController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired(required = false)
    private SearchHistoryMapper searchHistoryMapper;

    @Autowired(required = false)
    private SearchService searchService;

    /**
     * @param :
     * @return :
     * @author : hi
     * @date : 2022/6/10
     * @description : 记录搜索历史数据
     */
    @GetMapping("/Search")
    public RequestResult<List<Object>> Search(String userId, String searchCon) {

        SearchHistory searchHistory = new SearchHistory();
        searchHistory.setHistoryValue(searchCon);
        searchHistory.setHistoryKey(userId);
        if (redisUtils.hasKey(searchHistory.getHistoryKey())) {
            comm(searchHistory);
        } else {
            // redis中该用户没有搜索历史，去数据库判断是不是真没有这个historykey
            QueryWrapper<SearchHistory> searchHistoryQueryWrapper = new QueryWrapper<>();
            searchHistoryQueryWrapper.eq("history_key", userId);
            if (searchHistoryMapper.selectCount(searchHistoryQueryWrapper) == 0) {
                // 如果真的没有，添加redis和数据库
                redisTemplate.opsForList().leftPush(searchHistory.getHistoryKey(), searchHistory.getHistoryValue());
                //添加数据库
                searchService.addSearchKey(SearchHistoryConstant.Search_History_ADD_P2P, searchHistory);
            } else {
                // 数据库中有，但是redis中没有
                QueryWrapper<SearchHistory> searchHistoryQueryWrapper1 = new QueryWrapper<>();
                searchHistoryQueryWrapper1.eq("history_key", searchHistory.getHistoryKey());
                List<SearchHistory> searchHistories = searchHistoryMapper.selectList(searchHistoryQueryWrapper1);
                searchHistories.forEach(searchHistory1 -> redisTemplate.opsForList().leftPush(searchHistory1.getHistoryKey(), searchHistory1.getHistoryValue()));
            }
            comm(searchHistory);
        }
        List<Object> searchHistorys = redisTemplate.opsForList().range(searchHistory.getHistoryKey(), 0, -1);
        return ResultBuildUtil.success(searchHistorys);
    }

    /**
     *工具类
     */
    public void comm(SearchHistory searchHistory) {
        // 该用户有搜索历史
        if (redisTemplate.opsForList().remove(searchHistory.getHistoryKey(), 1, searchHistory.getHistoryValue()) == 0) {
            // 没有搜索过这个关键词
            if (redisTemplate.opsForList().size(searchHistory.getHistoryKey()) >= 10) {
                String o = (String) redisTemplate.opsForList().rightPop(searchHistory.getHistoryKey());
                //删除
                searchService.delSearchValue(SearchHistoryConstant.Search_History_DEl_P2P, o);
            } else {
            }
            redisTemplate.opsForList().leftPush(searchHistory.getHistoryKey(), searchHistory.getHistoryValue());

            //添加数据库
            searchService.addSearchKey(SearchHistoryConstant.Search_History_ADD_P2P, searchHistory);

        } else {
            // 搜索过这个关键词
            redisTemplate.opsForList().leftPush(searchHistory.getHistoryKey(), searchHistory.getHistoryValue());
            //删除
            searchService.delSearchValue(SearchHistoryConstant.Search_History_DEl_P2P, searchHistory.getHistoryValue());
            //添加数据库
            searchService.addSearchKey(SearchHistoryConstant.Search_History_ADD_P2P, searchHistory);
        }
    }
/**
 * @author : hi
 * @date   : 2022/6/13
 * @param  : [java.lang.Integer]
 * @return : com.kgc.scd.util.RequestResult<java.util.List<com.kgc.scd.bean.SearchHistory>>
 * @description : 查询历史记录
 */

    @PostMapping("/searchHistoryList")
    public  RequestResult<List<Object>> searchHistoryList (@RequestParam String historyKey){
        //QueryWrapper<SearchHistory> wrapper = new QueryWrapper<>();
        //wrapper.eq("history_key",historyKey);
        //wrapper.orderByDesc("history_date");
        //List<SearchHistory> searchHistories = searchHistoryMapper.selectList(wrapper);
        if (!redisUtils.hasKey(historyKey)) {
            // redis中该用户没有搜索历史，去数据库判断是不是真没有这个historykey
            QueryWrapper<SearchHistory> searchHistoryQueryWrapper = new QueryWrapper<>();
            searchHistoryQueryWrapper.eq("history_key", historyKey);
            if (searchHistoryMapper.selectCount(searchHistoryQueryWrapper) != 0) {
                // 数据库中有，但是redis中没有
                QueryWrapper<SearchHistory> searchHistoryQueryWrapper1 = new QueryWrapper<>();
                searchHistoryQueryWrapper1.eq("history_key", historyKey);
                List<SearchHistory> searchHistories = searchHistoryMapper.selectList(searchHistoryQueryWrapper1);
                searchHistories.forEach(searchHistory1 -> redisTemplate.opsForList().leftPush(searchHistory1.getHistoryKey(), searchHistory1.getHistoryValue()));
            }
        }
        List<Object> searchHistorys = redisTemplate.opsForList().range(historyKey, 0, -1);
        System.out.println(searchHistorys);
        return ResultBuildUtil.success(searchHistorys);
    }
}
